package cn.rui.controller.error;

import cn.rui.common.Result;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * 统一异常处理类
 * @author 徽州大都督
 * @date 2021/4/18
 */
@ControllerAdvice
public class ControllerExceptionAdvice {

    @ResponseBody
    @ExceptionHandler(RuntimeException.class)
    public Result handleRE(Exception ex){
       // String message = ex.getMessage ();
        return new Result(false,"系统错误，请联系管理员",null);
    }

    /**
     * 无权限配置
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(AccessDeniedException.class)
    public Result handleAccessRE(AccessDeniedException ex){
        return new Result (false,ex.getMessage(),null);
    }

    /**
     * 处理@Validated参数校验失败异常
     * @param ex 异常类
     * @return 响应x
     */
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(BindException.class)
    public Result handleMethodArgumentNotValidException(BindException ex){
        return Result.getFailure (ex.getBindingResult().getFieldError().getDefaultMessage());
    }

    /**
     * 自定义异常类
     * @param e
     * @return
     */
    @ExceptionHandler(MyExcetion.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public Result prodProcessOrderException(MyExcetion e) {
        return Result.getFailure ( e.getMessage());
    }


    /**
     * 用户名不存在
     * @param e
     * @return
     */
//    @ExceptionHandler(InternalAuthenticationServiceException.class)
//    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
//    @ResponseBody
//    public Result MyUsernameNotFoundException(InternalAuthenticationServiceException e) {
//        return Result.getFailure (e.getMessage ());
//    }
}
